package com.example.myweather.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DataBaseMapper {
	
	private String[] widgetsColumn = {DataBaseHandler.KEY_WIDGETS_ID,DataBaseHandler.KEY_WIDGETS_COUNTRY_NAME, DataBaseHandler.KEY_WIDGETS_CITY_NAME};
	
	//Make This Class Singleton
	public static DataBaseMapper instance;
	
	private DataBaseMapper(){}
	
	public static DataBaseMapper getInstance(){
		if(instance == null){
			instance =  new DataBaseMapper();
		}
		return instance;
	}
	
	public WidgetInitData getWidgetInitData(String widgetId, Context context){
		
		Log.d("DBM", widgetId);
		
		//Get Data Base Handler (my SqlLiteOpen Helper)
		DataBaseHandler dataBaseHandler = new DataBaseHandler(context);
		
		//Get Yawa DataBase
		SQLiteDatabase db = dataBaseHandler.getReadableDatabase();
		
		Cursor cursorWidgets = db.query(DataBaseHandler.TABLE_WIDGETS, this.widgetsColumn, DataBaseHandler.KEY_WIDGETS_ID + " = " + widgetId , null, null, null, null);
		
		if (cursorWidgets.getCount()==1)
			cursorWidgets.moveToFirst();
		else{
			cursorWidgets.close();
			db.close(); // Closing database connection
			Log.d("DBM", "Cursor Vacio");
			return null;
		}
		
		WidgetInitData widgetInitData = new WidgetInitData();
		
		widgetInitData.setWidgetId(cursorWidgets.getString(0));
		widgetInitData.setCountryName(cursorWidgets.getString(1));
		widgetInitData.setCityName(cursorWidgets.getString(2));
		
		cursorWidgets.close();
		db.close(); // Closing database connection
		// return Widget Init Data
		return widgetInitData;
	}
	
	
	public void addWidgetInitData(WidgetInitData widgetInitData, Context context){
		
		//Get Data Base Handler (my SqlLiteOpen Helper)
		DataBaseHandler dataBaseHandler = new DataBaseHandler(context);
				
		//Get Yawa DataBase
		SQLiteDatabase db = dataBaseHandler.getReadableDatabase();
		
		ContentValues values = new ContentValues();
		
		values.put(DataBaseHandler.KEY_WIDGETS_ID, widgetInitData.getWidgetId()); 
		
		values.put(DataBaseHandler.KEY_WIDGETS_COUNTRY_NAME,widgetInitData.getCountryName()); 
		
		values.put(DataBaseHandler.KEY_WIDGETS_CITY_NAME,widgetInitData.getCityName()); 
		
		// Inserting Row
		db.insert(DataBaseHandler.TABLE_WIDGETS, null, values);
		
		db.close(); // Closing database connection

	}
	
	
	
	
	// Deleting single Widget
	public void deleteWidget(WidgetInitData widgetInitData, Context context) {
		//Get Data Base Handler (my SqlLiteOpen Helper)
		DataBaseHandler dataBaseHandler = new DataBaseHandler(context);
						
		//Get Yawa DataBase
		SQLiteDatabase db = dataBaseHandler.getReadableDatabase();
			
		db.delete(DataBaseHandler.TABLE_WIDGETS, DataBaseHandler.KEY_WIDGETS_ID + " = ?",
				new String[] { widgetInitData.getWidgetId() });
		db.close();
	}

	
}
